package com.tengju.user.application.shared;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
* @author wuziyang
 * @Description: JWT工具类
*/
@Slf4j
@Component
public class JwtUtil {

    /**
     * 校验token是否正确
     */
    public static void verify(String token, String username, String password) {

        try {
            String RealToken = token.substring(Constant.LOGIN_TOKEN_PRE.length());
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(RealToken);
        } catch (Exception e) {
            throw ApplicationException.error(ApplicationExceptionCode.TOKEN_CHECK_FAIL,username,token);
        }


    }

    /**
     * 获得token中的信息无需password解密也能获得
     */
    public static String getUsername(String token) {
        try {
            if(StringUtils.isEmpty(token)){
                return null;
            }
            String realToken = token.substring(Constant.LOGIN_TOKEN_PRE.length());
            DecodedJWT jwt = JWT.decode(realToken);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            throw ApplicationException.error(ApplicationExceptionCode.DECRYPT_TOKEN_FAIL,token);
        }
    }

    /**
     * 生成token
     */
    public static String sign(String username, String password) {
        try {
            //token过期时间
            Date date = new Date(System.currentTimeMillis() + (Constant.LOGIN_TOKEN_EXPIRE_TIME * 1000));

            //密码加密
            Algorithm algorithm = Algorithm.HMAC256(password);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
//                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("生成token失败", e);
            throw ApplicationException.error(ApplicationExceptionCode.CREATE_TOKEN_FAIL,username);
        }
    }

    public static void main(String[] args) {
        System.out.println(sign("admin","123456"));
    }

}